<template>
  <div class="chat" @click="esc" id="chat">
    <div class="personnel-info" v-if="Number(person?.groupId)">
      <PersonnelIcon
        :name="person?.speakUser?.name"
        :headPortraits="person.groupInfo?.headPortrait"
      />
      <div class="person-right">
        <div class="person-right-name">
          {{ person?.groupInfo?.name }}
        </div>
        <div class="person-right-msg">公司名称</div>
      </div>
      <div>
        <icon-settings
          v-if="Number(person?.groupId)"
          size="24"
          @click="settingClick"
          style="color: #888"
        />
      </div>
    </div>

    <div
      class="personnel-info"
      v-if="!Number(person?.groupId) && person?.speakUserId === id"
    >
      <a-trigger
        trigger="click"
        :unmount-on-close="false"
        align-point
        @popup-visible-change="popupVisibleChange"
      >
        <PersonnelIcon
          :name="
            person?.listenUserId === userId
              ? person?.speakUser?.name
              : person?.listenUser?.name
          "
          :headPortraits="person?.listenUser?.headPortrait"
        />
        <template #content>
          <div class="demo-basic">
            <PersonnelInfoModal
              v-model:visible="personnelVisible"
              :data="person?.listenUser"
            />
          </div>
        </template>
      </a-trigger>
      <div class="person-right">
        <div
          class="person-right-name"
          style="line-height: 48px; margin-bottom: 0"
        >
          <!-- {{ props.msgLog }} -->
          {{
            person?.listenUserId === userId
              ? person?.speakUser?.name
              : person?.listenUser?.name
          }}
        </div>
        <!-- <div class="person-right-msg">公司名称</div> -->
      </div>
      <div>
        <!-- <icon-settings size="24" @click="settingClick" /> -->
      </div>
    </div>
    <div class="msg-box" ref="refMsgBox" @scroll="scrollEvent">
      <div class="no-more" v-if="props.noMore">没有更多了</div>
      <template v-if="msgLog.length !== 0">
        <div v-for="(item, index) in msgLog" :key="item.id">
          <div class="msg-box-time" v-if="noMore">
            {{ dayjs(msg[0].createdAt).format('YYYY-MM-DD HH:mm') }}
          </div>
          <div class="msg-box-time" v-else-if="index === 0">
            {{ dayjs(item.createdAt).format('YYYY-MM-DD HH:mm') }}
          </div>
          <div class="msg-box-time" v-else-if="index !== 0">
            {{
              compareTime(
                msgLog[index - 1].createdAt,
                msgLog[index].createdAt,
                'minute',
                5
              )
                ? dayjs(item.createdAt).format('YYYY-MM-DD HH:mm')
                : ''
            }}
          </div>
          <div v-if="item.speakUserId !== ownId" class="msg-box-other">
            <a-trigger
              trigger="click"
              :unmount-on-close="false"
              :popup-translate="[150, 10]"
              @popup-visible-change="popupVisibleChange"
            >
              <PersonnelIcon
                :name="
                  person?.groupId
                    ? item.speakUser?.name
                    : person?.listenUserId === userId
                    ? person?.speakUser?.name
                    : person?.listenUser?.name
                "
                :headPortraits="person?.speakUser?.headPortrait"
              />
              <template #content>
                <div class="demo-basic">
                  <PersonnelInfoModal
                    v-model:visible="personnelVisible"
                    :data="person?.speakUser"
                  />
                </div>
              </template>
            </a-trigger>
            <div class="spear-info">
              <div class="spear-name">
                {{
                  person?.groupId
                    ? item.speakUser?.name
                    : person?.listenUserId === userId
                    ? person?.speakUser?.name
                    : person?.listenUser?.name
                }}
              </div>
              <div
                class="msg-box-other-bubbles"
                :style="{
                  background: item.type === 4 ? '#fff' : '#c9e7ff',
                  'box-shadow': item.type === 4 ? '1px 1px 1px #999' : null
                }"
              >
                <!-- @contextmenu.prevent -->
                <div
                  style="width: 100; position: relative"
                  v-if="item.type === 1"
                >
                  <div
                    @click.right.prevent="rightssss(item)"
                    class="content"
                    v-html="item.content"
                  ></div>
                  <div v-show="item.show" class="setUp">
                    <div @click="copy(item)">复制</div>
                    <div @click="del(item, index)">删除</div>
                  </div>
                </div>
                <a-image
                  v-else-if="item.type === 5"
                  width="200"
                  height="125"
                  :src="item.content"
                />
                <div
                  v-else-if="item.type === 4"
                  @click="download(item.content.url)"
                  class="content fileDiv"
                >
                  <div>
                    <div>{{ item.content.name }}</div>
                    <div class="size">{{ item.content.size }}</div>
                  </div>
                  <icon-file style="color: rgb(4, 116, 32)" :size="50" />
                </div>
              </div>
            </div>
          </div>
          <div v-else class="msg-box-me">
            <div class="spear-info">
              <div class="spear-name">
                {{
                  person?.groupId
                    ? userInfo.name
                    : person?.speakUserId === userId
                    ? person?.speakUser?.name
                    : person?.listenUser?.name
                }}
              </div>
              <div
                class="msg-box-me-bubbles"
                :style="{
                  background: item.type === 4 ? '#fff' : '#c9e7ff',
                  'box-shadow': item.type === 4 ? '1px 1px 1px #999' : undefined
                }"
              >
                <div
                  style="width: 100; position: relative"
                  @click.right.prevent="rightssss(item)"
                >
                  <div
                    v-if="item.type === 1"
                    class="content"
                    v-html="item.content"
                  ></div>

                  <a-image
                    v-else-if="item.type === 5"
                    width="200"
                    height="125"
                    :src="item.content"
                  />
                  <div
                    v-else-if="item.type === 4"
                    @click="download(item.content.url)"
                    class="content fileDiv"
                  >
                    <div>
                      <div>{{ item.content.name }}</div>
                      <div class="size">{{ item.content.size }}</div>
                    </div>
                    <icon-file style="color: rgb(4, 116, 32)" :size="50" />
                  </div>
                  <div v-show="item.show" class="setUp">
                    <div v-if="item.type === 1" @click="copy(item)">复制</div>
                    <div @click="del(item, index)">删除</div>
                  </div>
                  <!-- {{ item.content }} -->
                </div>
              </div>
            </div>
            <a-trigger
              trigger="click"
              :unmount-on-close="false"
              :popup-translate="[-150, 10]"
              @popup-visible-change="popupVisibleChange"
            >
              <PersonnelIcon
                :name="
                  person?.groupId
                    ? userInfo.name
                    : person?.speakUserId === userId
                    ? person?.speakUser?.name
                    : person?.listenUser?.name
                "
                :headPortraits="person?.speakUser?.headPortrait"
              />
              <template #content>
                <div class="demo-basic">
                  <PersonnelInfoModal
                    v-model:visible="personnelVisible"
                    :data="person?.speakUser"
                  />
                </div>
              </template>
            </a-trigger>
          </div>
        </div>
      </template>
    </div>
    <div class="send-msg-box">
      <div class="groupInfo" v-show="groupInfoShow">
        <template
          v-for="info in person?.groupInfo?.name.split(',')"
          :key="info"
        >
          <div @click="isPerson(info)">{{ info }}</div>
        </template>
      </div>
      <div class="send-msg-box-utils">
        <a-space class="setting">
          <a-tooltip content="表情包">
            <a-popover title="" trigger="click" style="width: 400px">
              <icon-face-smile-fill size="24" style="color: #888" />
              <template #content>
                <div>
                  <span
                    style="font-size: 24px"
                    class="emoji"
                    @click="emojiClick(emoji)"
                    v-for="emoji in emojiList"
                    :key="emoji"
                    >{{ emoji }}</span
                  >
                </div>
              </template>
            </a-popover>
          </a-tooltip>
          <a-tooltip content="截图">
            <icon-camera
              @click="captureScreenshot"
              size="24"
              style="color: #888"
            />
          </a-tooltip>

          <a-tooltip content="文件">
            <a-popover title="" trigger="click" style="width: 180px">
              <icon-folder size="24" style="color: #888" />
              <template #content>
                <a-space direction="vertical">
                  <a-space style="cursor: pointer" @click="choiceFile">
                    <a-button style="width: 100%; background: #fff">
                      <icon-drive-file
                        size="20"
                        style="margin-right: 10px"
                      />上传文件
                    </a-button>
                  </a-space>
                  <!-- <a-space style="cursor: pointer">
                    <icon-folder size="20" />上传文件夹
                  </a-space> -->
                  <a-space style="cursor: pointer">
                    <a-popconfirm
                      content="选择上传路径"
                      okText="上传到个人文档"
                      cancelText="上传到公共文档"
                      @ok="ok"
                      @cancel="cancel"
                    >
                      <a-button style="background: #fff">
                        <icon-share-external
                          size="20"
                          style="margin-right: 10px"
                        />发送云端文件
                      </a-button>
                    </a-popconfirm>
                  </a-space>
                  <!-- <a-space><icon-cloud size="20" />发送云端文件夹</a-space> -->
                </a-space>
              </template>
            </a-popover>
          </a-tooltip>
        </a-space>
      </div>
      <div
        class="txt-word"
        contenteditable="true"
        ref="msgBox"
        @keydown="handleKeyDown"
      />
      <div class="send-btn">
        <div class="tip">Enter发送，Shift+Enter换行</div>
        <a-tooltip
          :popup-visible="popupVisible"
          background-color="#3491FA"
          position="tr"
        >
          <template #content>
            <span style="white-space: nowrap">消息不能为空！</span>
          </template>
          <a-button type="primary" @click="send">发送</a-button>
        </a-tooltip>
      </div>
    </div>
  </div>
  <div class="cut" v-if="imgUrl">
    <vue-cropper
      ref="cropper"
      :img="imgUrl"
      :output-size="1"
      output-type="png"
      :info="true"
      :full="false"
      :fixed="false"
      :fixed-number="[75.34]"
      :can-move="true"
      :can-move-box="true"
      :fixed-box="false"
      :original="false"
      :auto-crop="true"
      :auto-crop-width="750"
      :auto-crop-height="340"
      :center-box="true"
      @real-time="realTime"
      :high="true"
      @img-load="imgLoad"
      mode="contain"
      :max-img-size="99999"
      @crop-moving="cropMoving"
      @img-moving="imgMoving"
    ></vue-cropper>
    <div
      class="screenshot"
      v-show="flag"
      :style="{
        top: screenshotStyle.y + 10 + 'px',
        left: screenshotStyle.x - 142 + 'px'
      }"
    >
      <icon-close
        @click="imgUrl = ''"
        :size="25"
        style="color: red; cursor: pointer"
      />
      <icon-undo
        @click="rotateLeft"
        :size="25"
        style="color: #424242; margin-left: 10px; cursor: pointer"
      />
      <icon-redo
        @click="rotateRight"
        :size="25"
        style="color: #424242; margin-left: 10px; cursor: pointer"
      />
      <icon-check
        :size="25"
        @click="finish()"
        style="margin-left: 10px; color: blue; cursor: pointer"
      />
    </div>
  </div>
  <GroupSettingDrawer
    v-model:visible="settingVisible"
    :group-info="person"
    container="#char"
    @editGroupName="editGroupName"
  />
  <!-- <img
    id="screenshotImg"
    v-if="imgUrl"
    width="100%"
    :src="imgUrl"
    alt="暂无数据"
  /> -->
  <UploadModal
    :title="title"
    ref="uploadRef"
    @hide="userIdone = null"
  ></UploadModal>
  <UploadModalOne
    :title="title"
    :userId="userIdone"
    ref="uploadRefOne"
    @hide="userIdone = null"
  ></UploadModalOne>
</template>

<script setup lang="ts">
import {
  openChoiceFile,
  imgTypeList,
  officeTypeList,
  vidoeTypeList,
  audioTypeList
} from '@/utils/file';
import UploadModalOne from '@/views/Management/Home/Document/PersonalDocuments/UploadModal.vue';
import UploadModal from '@/views/Management/Home/Document/PublicDocuments/UploadModal.vue';
import { useUploadFileStore } from '@/store/index';
import dayjs from 'dayjs';
import { delImMsgLogList } from '@/apis/client/message/index';
import { compareTime } from '@/utils/utils';
import PersonnelIcon from './PersonnelIcon.vue';
import { Contacts, UserInfo } from '@/apis/client/message/type';
import GroupSettingDrawer from './GroupSettingDrawer.vue';
import { getContactGroupUserList } from '@/apis/client/addressBook';
import PersonnelInfoModal from './PersonnelInfoModal.vue';
import html2canvas from 'html2canvas';
import { MessageFile, fileLocation, UpLoadFile } from '@/utils/file';
import { FileUploadVerification } from '@/apis/document/documentCenter/index';
import { Message } from '@arco-design/web-vue';
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { UseBase64Return } from '@vueuse/core';

const props = withDefaults(
  defineProps<{
    person?: Contacts;
    msgLog?: Contacts[];
    noMore?: boolean;
    msgLogId: number;
  }>(),
  {
    noMore: false,
    msgLog: () => []
  }
);
const groupInfoShow = ref(false);
const cropper = ref();
const userId = +(localStorage.getItem('userId') + '');
const userInfo = JSON.parse(localStorage.getItem('userInfo') + '');
const uploadRefOne = ref();
const userIdone = ref();
const title = ref('');
const uploadRef = ref();
const imgUrl = ref();
const emit = defineEmits(['send', 'loadMoreHistory', 'update:person', 'renew']);
const id = Number(localStorage.getItem('userId'));
const clientHeight = ref(0);
const screenshotStyle = reactive({
  y: 625.5,
  x: 585
});

//滚动条触发事件
const scrollEvent = (e: any) => {
  if (
    // clientHeight元素内部高度
    e.srcElement.scrollTop + e.srcElement.clientHeight ==
    e.srcElement.scrollHeight
  ) {
    // more();
  }
  if (e.srcElement.scrollTop === 0) {
    if (!props.msgLog?.length) return;
    //记录当前窗口高度
    clientHeight.value = e.srcElement.scrollHeight;
    // emit('loadMoreHistory');
    emit('loadMoreHistory', props.msgLog[0].id, true);
  }
};
const emojiList = [
  '😀',
  '😃',
  '😄',
  '😁',
  '😆',
  '😅',
  '🤣',
  '😂',
  '🙂',
  '🙃',
  '😉',
  '😊',
  '😇',
  '🥰',
  '😍',
  '🤩',
  '😘',
  '😗',
  '😚',
  '😙',
  '🥲',
  '😋',
  '😛',
  '😜',
  '🤪',
  '😝',
  '🤑',
  '🤗',
  '🤭',
  '🤫',
  '🤔',
  '🤐',
  '🤨',
  '😐',
  '😑',
  '😶',
  '😏',
  '😒',
  '🙄',
  '😬',
  '🤥',
  '😌',
  '😔',
  '😪',
  '🤤',
  '😴',
  '😷',
  '🤒',
  '🤕',
  '🤢',
  '🤮',
  '🤧',
  '🥵',
  '🥶',
  '🥴',
  '😵',
  '🤯',
  '🤠',
  '🥳',
  '🥸',
  '😎',
  '🤓',
  '🧐',
  '😕',
  '😟',
  '🙁',
  '☹️',
  '😮',
  '😯',
  '😲',
  '😳',
  '🥺',
  '😦',
  '😧',
  '😨',
  '😰',
  '😥',
  '😢',
  '😭',
  '😱',
  '😖',
  '😣',
  '😞',
  '😓',
  '😩',
  '😫',
  '🥱',
  '😤',
  '😡',
  '😠',
  '🤬'
];
const flag = ref(true);
const cropMoving = (data) => {
  flag.value = !data.moving;
  screenshotStyle.x = data.axis.x2;
  screenshotStyle.y = data.axis.y2;
};
const finish = () => {
  cropper.value.getCropData(async (data: string) => {
    imgUrl.value = '';
    // //回传子组件base64
    const url = await MessageFile(data);
    msgBox.value.innerHTML =
      msgBox.value.innerHTML + `<img  width="100px" src="${url}" />`;
    // const match = msgBox.value.innerHTML.match(imgRegex).match(srcRegex);
    // const srcValue = match ? match[1] : null;
  });
};
const isPerson = (data: any) => {
  msgBox.value.innerHTML += `${data}&nbsp;&nbsp;`;
  groupInfoShow.value = false;
};
const rotateLeft = () => {
  cropper.value.rotateLeft();
  flag.value = true;
};
const rotateRight = () => {
  cropper.value.rotateRight();
  flag.value = true;
};
const emojiClick = (emoji: any) => {
  msgBox.value.innerHTML = msgBox.value.innerHTML + emoji;
};
const clearMsg = () => {
  msgBox.value.innerHTML = '';
};

const token = localStorage.getItem('token') as string;
const ownId = ref(Number(localStorage.getItem('userId')));
const popupVisible = ref(false);
const msgBox = ref();
const timer = ref();
let isCheckId = 0;
const rightssss = (e: any) => {
  esc();
  e.show = true;
  isCheckId = e.id;
};
const esc = () => {
  if (isCheckId) {
    props.msgLog.forEach((ele: any) => {
      if (ele.id === isCheckId) {
        ele.show = false;
      }
    });
  }
};
const copy = (e: any) => {
  let copyInput = document.createElement('input'); // 新增标签
  copyInput.value = e.content; // 标签赋值
  document.body.appendChild(copyInput); // 新增标签
  copyInput.select(); // 选取文本框内容
  document.execCommand('copy'); // 调用浏览器复制
  document.body.removeChild(copyInput); // 复制成功后再将构造的标签 移除
  e.show = false;
};
const del = async (e: any, index: number) => {
  await delImMsgLogList({ ids: [e.id] });
  // eslint-disable-next-line vue/no-mutating-props
  props.msgLog.splice(index, 1);
  // emit('renew', props.person);
  e.show = false;
};
// 键盘按下事件
const handleKeyDown = (event) => {
  if (groupInfoShow.value) {
    groupInfoShow.value = false;
  }
  if (event.key === '@' && props.person?.groupId) {
    console.log(1, event, props.person);
    groupInfoShow.value = true;
  }

  // 如果查看群基本信息的弹框没有弹出才能触发键盘发送事件
  if (!settingVisible.value) {
    if (event.shiftKey && event.key === 'Enter') {
      // 按下了Shift + Enter键，执行换行逻辑,并且每次重新获取光标的位置
      const selection = window.getSelection(); //  获取当前选区对象。
      const range = selection.getRangeAt(0); //获取选区中的第一个范围对象。
      const newlineNode = document.createElement('div'); //新增一个新的 <div> 元素，用于换行。
      newlineNode.innerHTML = '<br>'; //将新的 <div> 元素的内容设置为 <br>，即一个换行符。
      range.insertNode(newlineNode); //在选区范围内插入新的 <div> 元素。
      range.setStartAfter(newlineNode); //设置选区范围的起始位置在新的 <div> 元素之后。
      range.setEndAfter(newlineNode); //设置选区范围的结束位置在新的 <div> 元素之后。
      selection.removeAllRanges(); //移除所有选区范围
      selection.addRange(range); //将修改后的选区范围重新新增到选区对象中。
      event.preventDefault();
    } else if (event.key === 'Enter') {
      // 按下了Enter键，执行发送逻辑
      event.preventDefault();
      send();
    }
  }
};

let personnelVisible = ref(false); // 个人信息弹框
const popupVisibleChange = (val: boolean) => {
  if (val) {
    personnelVisible.value = true;
  }
};

const send = () => {
  const msg = msgBox.value.innerHTML;
  let trimStr = msg.trim();
  const imgRegex = /<img[^>]+>/g;
  let img = msgBox.value.innerHTML.match(imgRegex);
  if (img) {
    const splitArray = msgBox.value.innerHTML.split(imgRegex);
    if (!props.person) return;
    const { listenUserId, groupId, speakUserId, speakUser } = props.person;
    if (splitArray[0]) {
      const data: any = {
        // speakUserId: ownId.value,
        listenUserId: listenUserId === ownId.value ? speakUserId : listenUserId,
        content: splitArray[0],
        type: 1,
        groupId
      };
      if (groupId) {
        data.speakUser = { id: userInfo.id, name: userInfo.name };
      }
      emit('send', data);
    }
    const srcRegex = /src="([^"]+)"/;
    const match = img[0].match(srcRegex);
    const url = match ? match[1] : null;
    const data = {
      // speakUserId: ownId.value,
      listenUserId: listenUserId === ownId.value ? speakUserId : listenUserId,
      content: url,
      type: 5,
      groupId
    };
    emit('send', data);
    if (splitArray[1]) {
      const data: any = {
        // speakUserId: ownId.value,
        listenUserId: listenUserId === ownId.value ? speakUserId : listenUserId,
        content: splitArray[0],
        type: 1,
        groupId
      };
      if (groupId) {
        data.speakUser = { id: userInfo.id, name: userInfo.name };
      }
      emit('send', data);
    }
    msgBox.value.innerHTML = '';
    return;
  }
  trimStr = clearBr(trimStr);
  if (timer.value) {
    clearTimeout(timer.value);
  }
  if (!trimStr) {
    popupVisible.value = true;
    timer.value = setTimeout(() => {
      popupVisible.value = false;
    }, 2000);
    return;
  }
  msgBox.value.innerHTML = '';
  if (!props.person) return;
  const { listenUserId, groupId, speakUserId, speakUser } = props.person;
  const data: any = {
    // speakUserId: ownId.value,
    listenUserId: listenUserId === ownId.value ? speakUserId : listenUserId,
    content: msg,
    type: 1,
    groupId
  };
  if (groupId) {
    data.speakUser = { id: userInfo.id, name: userInfo.name };
  }
  emit('send', data);
};
//去除换行
const clearBr = (str: string): string => {
  str = str.replace(/<\/?.+?>/g, '');
  str = str.replace(/[\r\n]/g, '');
  return str;
};
const isShift = ref(0);
const isEnter = ref(0);
const refMsgBox = ref();
/**
 * 滚动至底
 */
const scrollToBottom = () => {
  refMsgBox.value.scrollTop = refMsgBox.value.scrollHeight;
  // console.log('refMsgBox.value', refMsgBox.value);
};

watch(
  () => props.msgLog?.length,
  (newValue, old) => {
    //数据<=10条，说明是首次进来，否则是加载历史记录
    //发送消息滚动至底
    nextTick(() => {
      if (
        (props.msgLog && props.msgLog?.length <= 10) ||
        (newValue &&
          old &&
          props.msgLog &&
          props.msgLog[newValue - 2].id === props.msgLog[old - 1].id)
      ) {
        scrollToBottom();
      } else {
        refMsgBox.value.scrollTop =
          refMsgBox.value.scrollHeight - clientHeight.value;
      }
    });
  }
);

const settingVisible = ref(false);

const settingClick = () => {
  settingVisible.value = true;
  getGroupUser();
};
const chat = ref();
const groupUserList = ref([]);
const getGroupUser = async () => {
  const id = props.person?.groupId;
  if (!id) return;
  const res = await getContactGroupUserList({
    id,
    pageNumber: 0,
    pageSize: -1
  });
  groupUserList.value = res.content || [];
};
const editGroupName = (name: string) => {
  /* eslint-disable */
  props.person.groupInfo.name = name;
  emit('update:person', props.person, name);
};
const captureScreenshot = async () => {
  const imgRegex = /<img[^>]+>/g;
  let imgVlaue = msgBox.value.innerHTML.match(imgRegex);
  if (imgVlaue) {
    return Message.error('只能上传一个图片');
  }
  // 获取要截图的元素
  const targetElement = document.querySelector('#app') as HTMLElement;
  html2canvas(targetElement, {
    //superMap整个页面的节点
    backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
    useCORS: true, //支持图片跨域
    scale: 1 //设置放大的倍数
  }).then(async (canvas) => {
    try {
      //截图用img元素承装，显示在页面的上
      let img = new Image();
      img.src = canvas.toDataURL('image/jpg'); // toDataURL :图片格式转成 base64
      imgUrl.value = img.src;
      // //回传子组件base64
      // const url = await MessageFile(img.src);
      // // msgBox.value.innerHTML =
      // //   msgBox.value.innerHTML +
      // //   `<img  width="100px" height="100px" src="${url}"/> `;
      // // const txtWord = document.querySelector('.txt-word') as HTMLElement;
      // // txtWord.innerHTML = `<img  width="100px" height="100px" src="${url}"/> `;
      // if (!props.person) return;
      // const { listenUserId, groupId, speakUserId } = props.person;
      // const data = {
      //   // speakUserId: ownId.value,
      //   listenUserId: listenUserId === ownId.value ? speakUserId : listenUserId,
      //   content: url,
      //   type: 5,
      //   groupId
      // };
      // emit('send', data);
    } catch (error) {
      // console.log(111, error);
    }
  });
};

const choiceFile = async () => {
  try {
    const [file] = await openChoiceFile(
      [...imgTypeList, ...officeTypeList, ...vidoeTypeList, ...audioTypeList],
      1,
      0
    );

    const fileUr = await UpLoadFile([file][0]);
    if (!props.person) return;
    const { listenUserId, groupId, speakUserId } = props.person;
    const data: any = {
      // speakUserId: ownId.value,
      listenUserId: listenUserId === ownId.value ? speakUserId : listenUserId,
      content: file.type.startsWith('image/')
        ? fileUr
        : JSON.stringify({
            url: fileUr,
            name: file.name,
            size: formatFileSize(file.size)
          }),
      type: file.type.startsWith('image/') ? 5 : 4,
      groupId
    };
    emit('send', data);
  } catch (error) {
    Message.error('上传失败');
    console.log(error);
  }
};
function formatFileSize(size: number) {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  }
}
const download = (url: string) => {
  // let a = document.createElement('a');
  // a.style.display = 'none';
  // a.href = url;
  // a.download;
  // a.setAttribute('download', ''); //download属性
  // console.log(' =', a, url);
  // a.click();
  window.open(url);
};
const cancel = () => {
  title.value = '公共文档';
  uploadRef.value.visible = true;
};
const ok = () => {
  //
  title.value = '个人文档';
  userIdone.value = +(localStorage.getItem('userId') + '');
  uploadRefOne.value.visible = true;
};
defineExpose({ clearMsg });
</script>
<style lang="less" scoped>
.chat {
  height: 100%;
  display: flex;
  flex-direction: column;
  .personnel-info {
    border-bottom: 1px solid #ebebeb;
    display: flex;
    align-items: center;
    padding: 10px 16px;
    .person-right {
      height: 100%;
      flex: 1;
      padding: 0 8px;
      display: flex;
      align-items: flex-start;
      flex-direction: column;

      &-name {
        font-size: 18px;
        color: #333;
        margin-bottom: 10px;
      }
      &-msg {
        font-size: 14px;
        color: #999;
        overflow: hidden;
        width: 100px;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .msg-box {
    flex: 1;
    border-bottom: 1px solid #ebebeb;
    overflow: auto;
    padding: 0 10px;
    font-size: 16px;
    background-color: #fff;
    .no-more {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
    }
    &-time {
      margin: 20px 0;
      text-align: center;
      color: #999;
    }
    &-other {
      display: flex;
      margin: 16px;
      .spear-info {
        width: 100%;
        .spear-name {
          margin-left: 10px;
          margin-bottom: 5px;
          color: #999;
          cursor: pointer;
        }
        .msg-box-other-bubbles {
          margin-left: 10px;
          width: fit-content;
          background: white;
          padding: 10px;
          border-radius: 5px;
          // max-width: 300px;
          max-width: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          white-space: pre-wrap;
          // white-space: normal;
          word-break: break-all;
          .content {
            display: flex;
            width: 100%;
          }
          .setUp {
            position: absolute;
            width: 80px;
            top: 0;
            right: -70px;
            background: #fff;
            text-align: center;
            padding: 5px;
            border-radius: 5px;
            border: 1px solid #7f7979;
            color: #7f7979;
            div {
              cursor: pointer;
              margin-bottom: 5px;
            }
          }
          .fileDiv {
            a {
              text-decoration: none;
              color: inherit;
            }
            cursor: pointer;
            padding: 10px;
            width: 160px;
            height: 60px;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            .size {
              margin-top: 10px;
              color: #00000054;
              font-size: 12px;
            }
          }
        }
      }
    }
    &-me {
      display: flex;
      justify-content: flex-end;
      margin: 16px;
      text-align: right;
      .spear-info {
        width: 100%;
        // text-align: right;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        .spear-name {
          margin-right: 10px;
          margin-bottom: 5px;
          color: #999;
          cursor: pointer;
        }
        .msg-box-me-bubbles {
          text-align: left;
          margin-right: 10px;
          background: #c9e7ff;
          width: fit-content;
          padding: 10px;
          border-radius: 5px;
          max-width: 50%;

          display: flex;
          align-items: center;
          justify-content: center;
          // white-space: pre-wrap;
          white-space: normal;
          word-break: break-all;
          .content {
            display: flex;
            width: 100%;
          }
          .setUp {
            position: absolute;
            width: 80px;
            top: 0;
            right: 20px;
            background: #fff;
            text-align: center;
            padding: 5px;
            border-radius: 5px;
            border: 1px solid #7f7979;
            color: #7f7979;
            div {
              cursor: pointer;
              margin-bottom: 5px;
            }
          }
          .fileDiv {
            a {
              text-decoration: none;
              color: inherit;
            }
            cursor: pointer;
            padding: 10px;
            width: 160px;
            height: 60px;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;

            .size {
              margin-top: 10px;
              color: #00000054;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
  .send-msg-box {
    // height: 300px;
    // background: white;
    padding: 0 10px;
    position: relative;
    .groupInfo {
      position: absolute;
      height: 100px;
      width: 120px;
      top: -110px;
      padding: 5px;
      left: 50px;
      overflow: auto;
      background: #ececee;
      border-radius: 5px;
      div {
        padding: 5px;
        border-radius: 5px;
        margin-bottom: 10px;
        background: #ececee;
        cursor: pointer;
      }
      div:hover {
        background: #fff;
      }
    }
    .txt-word {
      height: 100px;
      padding: 5px;
      white-space: normal;
      word-break: break-all;
      font-size: 16px;
      overflow: auto;
    }
    .txt-word:focus {
      border: none;
      outline: none;
    }
    &-utils {
      margin: 5px 0;
      .emoji {
        font-size: 18px;
        background: #eee;
        cursor: pointer;
      }
      .setting {
        :deep(.arco-space-item) {
          cursor: pointer;
          margin-right: 10px !important;
        }
      }
    }
    .send-btn {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .tip {
        color: #bababa;
        margin-right: 16px;
      }
    }
  }
}
:deep(.arco-textarea-mirror) {
  height: 100%;
}
/* 定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸 */
::-webkit-scrollbar {
  z-index: 100;
  width: 6px;
  height: 6px;
  background-color: #fff;
}

// /* 定义滚动条轨道 内阴影+圆角 */
::-webkit-scrollbar-track {
  z-index: 100;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgb(144 147 153 / 30%);
}

// /* 定义滑块 内阴影+圆角 */
::-webkit-scrollbar-thumb {
  z-index: 100;
  background-color: rgb(169 169 169 / 50%);
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgb(144 147 153 / 30%);
}
.cut {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  // /* opacity: 0.5; */
  // /* background: #999; */
  z-index: 999;
}
.chat-container {
  width: 100%;
  height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.chat-message {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

.message-sender {
  font-weight: bold;
  color: #333;
}

.message-content {
  display: flex;
  align-items: center;
}

.file-preview {
  width: 80px;
  height: 80px;
  margin-right: 10px;
}

.file-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-details {
  display: flex;
  flex-direction: column;
}

.file-name {
  font-weight: bold;
  color: #333;
}

.file-size {
  color: #888;
}
.screenshot {
  position: fixed;
  // top: 635.5px;
  // right: 585px;
  background: #ffffffa8;
  border: 1px solid #6d818f;
  border-radius: 5px;
  padding: 5px;
  display: flex;
  justify-content: end;
}
</style>
